<template>
  <div class="ranking-page">
    <van-nav-bar title="考试排名" left-arrow @click-left="onClickLeft" />

    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <template v-else-if="examInfo && rankings.length > 0">
      <div class="content-container">
        <!-- 考试信息 -->
        <div class="exam-info-card">
          <div class="exam-title">{{ examInfo.title }}</div>
          <div class="exam-stats">
            <span>参与人数: {{ rankings.length }}</span>
            <span>平均分: {{ calculateAverageScore() }}</span>
          </div>
        </div>

        <!-- 我的排名 -->
        <div v-if="myRanking" class="my-ranking-card">
          <div class="card-title">我的排名</div>
          <div class="my-rank-info">
            <div class="rank-badge" :class="getRankBadgeClass(myRanking.rank)">
              第 {{ myRanking.rank }} 名
            </div>
            <div class="my-score">{{ myRanking.score }} 分</div>
            <div class="beat-percentage">
              超过了 {{ calculateBeatPercentage(myRanking.rank) }}% 的考生
            </div>
          </div>
        </div>

        <!-- 排名列表 -->
        <div class="ranking-list-card">
          <div class="card-title">排名榜</div>
          <div class="ranking-list">
            <div
              v-for="item in rankings"
              :key="item.user_id"
              class="ranking-item"
              :class="{ 'is-current-user': item.user_id === currentUserId }"
            >
              <div class="rank-number" :class="getRankClass(item.rank)">
                <van-icon
                  v-if="item.rank <= 3"
                  :name="getRankIcon(item.rank)"
                />
                <span v-else>{{ item.rank }}</span>
              </div>
              <div class="user-info">
                <div class="username">
                  {{ item.username || `用户${item.user_id.slice(-4)}` }}
                </div>
                <div class="exam-time">
                  {{ formatDateTime(item.submit_time) }}
                </div>
              </div>
              <div class="score-info">
                <div class="score">{{ item.score }}</div>
                <div class="total-score">/ {{ item.total_score }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分数分布 -->
        <div class="score-distribution-card">
          <div class="card-title">分数分布</div>
          <div class="distribution-chart">
            <div
              v-for="range in scoreDistribution"
              :key="range.label"
              class="distribution-item"
            >
              <div class="range-label">{{ range.label }}</div>
              <div class="range-bar">
                <div
                  class="range-fill"
                  :style="{ width: `${range.percentage}%` }"
                ></div>
              </div>
              <div class="range-count">{{ range.count }}人</div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <div v-else class="empty-state">
      <van-empty description="暂无排名数据" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  ref,
} from 'vue';

import { showToast } from 'vant';
import {
  useRoute,
  useRouter,
} from 'vue-router';

import { examApi } from '../../api/modules/exam';
import { useUserStore } from '../../stores/user';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loading = ref(true);
const examInfo = ref<any>(null);
const rankings = ref<any[]>([]);
const myRanking = ref<any>(null);

const currentUserId = computed(() => userStore.user?.id || userStore.user?._id);

// 获取排名数据
onMounted(async () => {
  const examId = route.params.id as string;
  if (!examId) {
    showToast("未找到考试ID");
    router.replace("/home");
    return;
  }

  try {
    // 获取考试信息
    const examResponse = await examApi.getExamDetail(examId);
    examInfo.value = examResponse.data;

    // 获取排名数据
    const rankingResponse = await examApi.getExamRanking(examId);
    rankings.value = rankingResponse.data.rankings || [];

    // 查找我的排名
    if (currentUserId.value) {
      myRanking.value = rankings.value.find(
        (item) => item.user_id === currentUserId.value
      );
    }

    console.log("排名数据:", {
      exam: examInfo.value,
      rankings: rankings.value,
      myRanking: myRanking.value,
    });
  } catch (error) {
    console.error("获取排名数据失败", error);
    showToast("获取排名数据失败");
  } finally {
    loading.value = false;
  }
});

// 计算平均分
const calculateAverageScore = () => {
  if (rankings.value.length === 0) return 0;
  const totalScore = rankings.value.reduce((sum, item) => sum + item.score, 0);
  return Math.round(totalScore / rankings.value.length);
};

// 计算超过的百分比
const calculateBeatPercentage = (rank: number) => {
  if (rankings.value.length === 0) return 0;
  const percentage =
    ((rankings.value.length - rank) / rankings.value.length) * 100;
  return Math.round(percentage);
};

// 获取排名徽章样式
const getRankBadgeClass = (rank: number) => {
  if (rank === 1) return "rank-first";
  if (rank === 2) return "rank-second";
  if (rank === 3) return "rank-third";
  if (rank <= 10) return "rank-top10";
  return "rank-normal";
};

// 获取排名样式
const getRankClass = (rank: number) => {
  if (rank === 1) return "rank-gold";
  if (rank === 2) return "rank-silver";
  if (rank === 3) return "rank-bronze";
  return "";
};

// 获取排名图标
const getRankIcon = (rank: number) => {
  if (rank === 1) return "medal";
  if (rank === 2) return "medal-o";
  if (rank === 3) return "medal-o";
  return "";
};

// 分数分布
const scoreDistribution = computed(() => {
  if (rankings.value.length === 0) return [];

  const ranges = [
    { label: "90-100分", min: 90, max: 100 },
    { label: "80-89分", min: 80, max: 89 },
    { label: "70-79分", min: 70, max: 79 },
    { label: "60-69分", min: 60, max: 69 },
    { label: "60分以下", min: 0, max: 59 },
  ];

  const maxCount = Math.max(
    ...ranges.map((range) => {
      return rankings.value.filter(
        (item) => item.score >= range.min && item.score <= range.max
      ).length;
    }),
    1
  ); // 防止除零

  return ranges.map((range) => {
    const count = rankings.value.filter(
      (item) => item.score >= range.min && item.score <= range.max
    ).length;

    return {
      ...range,
      count,
      percentage: maxCount > 0 ? (count / maxCount) * 100 : 0,
    };
  });
});

// 格式化时间
const formatDateTime = (dateTime: string) => {
  const date = new Date(dateTime);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = String(date.getMinutes()).padStart(2, "0");

  return `${month}/${day} ${hour}:${minute}`;
};

// 返回上一页
const onClickLeft = () => {
  router.back();
};
</script>

<style scoped>
.ranking-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-container {
  padding: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.empty-state {
  padding: 32px 16px;
}

/* 考试信息卡片 */
.exam-info-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.exam-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.exam-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #969799;
}

/* 我的排名卡片 */
.my-ranking-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
}

.my-rank-info {
  text-align: center;
  padding: 16px;
}

.rank-badge {
  display: inline-block;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
}

.rank-first {
  background-color: #ffd700;
  color: #333;
}

.rank-second {
  background-color: #c0c0c0;
  color: #333;
}

.rank-third {
  background-color: #cd7f32;
  color: #fff;
}

.rank-top10 {
  background-color: #1989fa;
  color: #fff;
}

.rank-normal {
  background-color: #f2f3f5;
  color: #646566;
}

.my-score {
  font-size: 24px;
  font-weight: 700;
  color: #1989fa;
  margin-bottom: 4px;
}

.beat-percentage {
  font-size: 14px;
  color: #969799;
}

/* 排名列表 */
.ranking-list-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.ranking-list {
  margin-top: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f2f3f5;
}

.ranking-item:last-child {
  border-bottom: none;
}

.is-current-user {
  background-color: rgba(25, 137, 250, 0.05);
  margin: 0 -16px;
  padding: 12px 16px;
  border-radius: 8px;
}

.rank-number {
  width: 32px;
  height: 32px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-right: 12px;
  background-color: #f2f3f5;
  color: #646566;
}

.rank-gold {
  background-color: #ffd700;
  color: #333;
}

.rank-silver {
  background-color: #c0c0c0;
  color: #333;
}

.rank-bronze {
  background-color: #cd7f32;
  color: #fff;
}

.user-info {
  flex: 1;
  margin-right: 12px;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 2px;
}

.exam-time {
  font-size: 12px;
  color: #969799;
}

.score-info {
  text-align: right;
}

.score {
  font-size: 18px;
  font-weight: 600;
  color: #1989fa;
}

.total-score {
  font-size: 12px;
  color: #969799;
}

/* 分数分布 */
.score-distribution-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.distribution-chart {
  margin-top: 12px;
}

.distribution-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.distribution-item:last-child {
  margin-bottom: 0;
}

.range-label {
  width: 80px;
  font-size: 14px;
  color: #646566;
}

.range-bar {
  flex: 1;
  height: 8px;
  background-color: #f2f3f5;
  border-radius: 4px;
  overflow: hidden;
  margin: 0 12px;
}

.range-fill {
  height: 100%;
  background-color: #1989fa;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.range-count {
  width: 40px;
  text-align: right;
  font-size: 14px;
  color: #969799;
}
</style>
